import pandas as pd
df = pd.read_csv('merge.csv')
df['create_time'] = pd.to_datetime(df['create_time'])
df['年份'] = df['create_time'].dt.year
df['月份'] = df['create_time'].dt.month
df['季度'] = (df['月份'] - 1) // 3 + 1
grouped = df.groupby(['khmc', '年份', '季度','月份']).size().reset_index(name='购买次数')
top_customers_per_quarter = (grouped.groupby(['年份', '季度','月份']).apply(lambda x: x.sort_values(by='购买次数', ascending=False).head(3)).reset_index(drop=True))
top_customers_per_quarter.set_index(['年份', '季度','月份', 'khmc'], inplace=True)
print("\n设置多层索引后的结果:")
print(top_customers_per_quarter)
top_customers_per_quarter.to_csv('top_customers_per_quarter.csv')